import React, { useState, useEffect } from 'react';
import { Input, Button, Select, Space } from 'antd';
import { Link } from 'react-router-dom';
import { ArrowLeftOutlined } from '@ant-design/icons';

const TimestampTool = () => {
  const [currentTimestamp, setCurrentTimestamp] = useState(Math.floor(Date.now() / 1000));
  const [isRunning, setIsRunning] = useState(false);
  const [inputTimestamp, setInputTimestamp] = useState('');
  const [timestampResult, setTimestampResult] = useState('');
  const [dateTimeInput, setDateTimeInput] = useState({
    year: '',
    month: '',
    day: '',
    hour: '',
    minute: '',
    second: ''
  });
  const [dateTimeResult, setDateTimeResult] = useState('');
  const [timestampUnit, setTimestampUnit] = useState('秒');

  useEffect(() => {
    let interval;
    if (isRunning) {
      interval = setInterval(() => {
        setCurrentTimestamp(Math.floor(Date.now() / 1000));
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [isRunning]);

  const handleStart = () => setIsRunning(true);
  const handleStop = () => setIsRunning(false);
  const handleReset = () => setCurrentTimestamp(Math.floor(Date.now() / 1000));

  const convertTimestampToDate = () => {
    if (!inputTimestamp) {
      setTimestampResult('');
      return;
    }
    try {
      const multiplier = timestampUnit === '秒' ? 1000 : 1;
      const timestamp = parseInt(inputTimestamp);
      const date = new Date(timestamp * multiplier);
      setTimestampResult(date.toISOString().slice(0, 19).replace('T', ' '));
    } catch (e) {
      setTimestampResult('无效的时间戳');
    }
  };

  const convertDateToTimestamp = () => {
    const { year, month, day, hour, minute, second } = dateTimeInput;
    if (!year || !month || !day) {
      setDateTimeResult('');
      return;
    }
    try {
      const date = new Date(
        year,
        month - 1,
        day,
        hour || 0,
        minute || 0,
        second || 0
      );
      const timestamp = Math.floor(date.getTime() / 1000);
      setDateTimeResult(timestamp.toString());
    } catch (e) {
      setDateTimeResult('无效的日期');
    }
  };

  return (
    <div className="tool-container">
      <div className="tool-header">
        <Link to="/" className="back-button">
          <ArrowLeftOutlined />
          返回工具箱
        </Link>
        <div className="tool-title">时间戳转换</div>
      </div>
      
      <div className="tool-content timestamp-tool">
        <div className="current-timestamp-section">
          <div className="section-row">
            <span className="label">现在的Unix时间戳(Unix timestamp)是：</span>
            <span className="timestamp">{currentTimestamp}</span>
            <Space>
              <Button onClick={handleStart} type="primary">开始</Button>
              <Button onClick={handleStop}>停止</Button>
              <Button onClick={handleReset}>刷新</Button>
            </Space>
          </div>
        </div>

        <div className="conversion-section">
          <div className="conversion-block">
            <div className="section-row">
              <span className="label">Unix时间戳 (Unix timestamp)</span>
              <Input 
                value={inputTimestamp}
                onChange={(e) => setInputTimestamp(e.target.value)}
                style={{ width: 200 }}
              />
              <Select
                value={timestampUnit}
                onChange={setTimestampUnit}
                style={{ width: 80 }}
              >
                <Select.Option value="秒">秒</Select.Option>
                <Select.Option value="毫秒">毫秒</Select.Option>
              </Select>
              <Button type="primary" onClick={convertTimestampToDate}>转换</Button>
            </div>
            <div className="result-row">
              <span className="label">转换结果：</span>
              <Input 
                value={timestampResult}
                readOnly
                style={{ width: 280 }}
              />
            </div>
          </div>

          <div className="conversion-block">
            <div className="section-row datetime-input">
              <span className="label">时间 (年/月/日 时:分:秒)</span>
              <Space>
                <Input
                  placeholder="年"
                  value={dateTimeInput.year}
                  onChange={(e) => setDateTimeInput({...dateTimeInput, year: e.target.value})}
                  style={{ width: 80 }}
                />
                <Input
                  placeholder="月"
                  value={dateTimeInput.month}
                  onChange={(e) => setDateTimeInput({...dateTimeInput, month: e.target.value})}
                  style={{ width: 60 }}
                />
                <Input
                  placeholder="日"
                  value={dateTimeInput.day}
                  onChange={(e) => setDateTimeInput({...dateTimeInput, day: e.target.value})}
                  style={{ width: 60 }}
                />
                <Input
                  placeholder="时"
                  value={dateTimeInput.hour}
                  onChange={(e) => setDateTimeInput({...dateTimeInput, hour: e.target.value})}
                  style={{ width: 60 }}
                />
                <Input
                  placeholder="分"
                  value={dateTimeInput.minute}
                  onChange={(e) => setDateTimeInput({...dateTimeInput, minute: e.target.value})}
                  style={{ width: 60 }}
                />
                <Input
                  placeholder="秒"
                  value={dateTimeInput.second}
                  onChange={(e) => setDateTimeInput({...dateTimeInput, second: e.target.value})}
                  style={{ width: 60 }}
                />
              </Space>
              <Button type="primary" onClick={convertDateToTimestamp}>转换Unix时间戳</Button>
            </div>
            <div className="result-row">
              <span className="label">转换结果：</span>
              <Input 
                value={dateTimeResult}
                readOnly
                style={{ width: 280 }}
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default TimestampTool;
